package com.aabte.nettyleran.netty.privateprotocolstack;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/15
 */
public class HeartBeatRespHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;

        if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
            // 心跳应答消息
            System.out.println("Receive client heart beat message: " + message);

            NettyMessage heatBeatMsg = buildHeatBeatMsg();

            System.out.println("Send heart beat response message to client: " + heatBeatMsg);
            ctx.writeAndFlush(heatBeatMsg);
        }
    }

    private NettyMessage buildHeatBeatMsg() {
        Header header = Header.builder()
                .type(MessageType.HEARTBEAT_RESP.value())
                .attachment(new HashMap<>(0))
                .build();

        return NettyMessage.builder()
                .header(header)
                .build();
    }
}
